#ifndef TINYXMLCONFIG_H
#define TINYXMLCONFIG_H

#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include "tinyxml.h"
using namespace std;

class TiXmlConfig{
public:
    TiXmlConfig(const char *filename):isValic(true){
        if(!doc.LoadFile(filename)){
            cerr << doc.ErrorDesc() << endl;
            isValic = false;
            return;
        }
        TiXmlElement* elem = doc.FirstChildElement();
        if(!elem){
            cerr << "Failed to load file: No root element." << endl;
            isValic = false;
            doc.Clear();
            return;
        }
        for(elem=elem->FirstChildElement(); elem; elem = elem->NextSiblingElement()){
            vIterm.push_back(*elem);
        }
        doc.Clear();
    }
    bool GetStatus(){return isValic;}
    int getSize(){return vIterm.size();}
    string getTitle(int i){
        if(i>=getSize() || i<0)return NULL;
        return (string)vIterm[i].Value();
    }
    string getContent(int i){
        if(i>=getSize() || i<0)return NULL;
        return (string)vIterm[i].FirstChild()->Value();
    }

private:
    bool isValic;
    vector<TiXmlElement> vIterm;
    TiXmlDocument doc;
};

class TiXmlData{
public:
    TiXmlData(const char *filename):isValic(true){
        if(!doc.LoadFile(filename)){
            cerr << doc.ErrorDesc() << endl;
            isValic = false;
            return;
        }
        TiXmlElement* elem = doc.FirstChildElement();
        if(!elem){
            cerr << "Failed to load file: No root element." << endl;
            isValic = false;
            doc.Clear();
            return;
        }
        for(elem=elem->FirstChildElement(); elem; elem = elem->NextSiblingElement()){
            vIterm.push_back(*elem);
        }
        doc.Clear();
    }
    ~TiXmlData(){
        isValic = false;
        doc.Parse( "<!-- data save file -->" );
        TiXmlElement* data = new TiXmlElement("DATA");
        doc.LinkEndChild(data);
        for(int i=0;i<getSize();i++){
            TiXmlElement* elem = new TiXmlElement(getTitle(i).c_str());
            TiXmlText* text = new TiXmlText(getContent(i).c_str());
            data->LinkEndChild(elem);
            elem->LinkEndChild(text);
        }
        if(!doc.SaveFile()){
            cerr << doc.ErrorDesc() << endl;
        }
        doc.Clear();
    }

    bool GetStatus(){return isValic;}
    int getSize(){return vIterm.size();}
    string getTitle(int i){
        if(i>=getSize() || i<0)return NULL;
        return (string)vIterm[i].Value();
    }
    string getContent(int i){
        if(i>=getSize() || i<0)return NULL;
        return (string)vIterm[i].FirstChild()->Value();
    }
    void setContent(int i,string value){
        if(i>=getSize() || i<0)return;
        vIterm[i].FirstChild()->SetValue(value.c_str());
    }

private:
    bool isValic;
    vector<TiXmlElement> vIterm;
    TiXmlDocument doc;
};

#endif // TINYXMLCONFIG_H
